package com.lishe.lishe.lishe.module.excitation.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.lishe.lishe.Imageloader.ImageLoaderUtils;
import com.lishe.lishe.R;
import com.lishe.lishe.lishe.MyRecyclerView.RecyclerLinearViewItemDecoration;
import com.lishe.lishe.lishe.MyRecyclerView.RecyclerViewRefreshListener;
import com.lishe.lishe.lishe.MyRecyclerView.RecyclerviewBaseAdapter;
import com.lishe.lishe.lishe.MyRecyclerView.RefreshRecyclerView;
import com.lishe.lishe.lishe.base.BaseActivity;
import com.lishe.lishe.lishe.bean.DianZanObject;
import com.lishe.lishe.lishe.common.Globals;
import com.lishe.lishe.lishe.module.excitation.adapter.DianZanWallAdapter;
import com.lishe.lishe.lishe.module.excitation.dialog.ShowFullScreenImageDialog;
import com.lishe.lishe.lishe.module.excitation.dialog.ShowSendCommentDialog;
import com.lishe.lishe.lishe.module.excitation.dialog.ShowSendGiftDialog;
import com.lishe.lishe.lishe.module.excitation.fragment.DianZanWallFragment;
import com.lishe.lishe.lishe.module.excitation.http.HttpExcitation;
import com.lishe.lishe.lishe.module.excitation.interfaces.OnDianZanWallClickListener;
import com.lishe.lishe.lishe.module.excitation.interfaces.OnMessageChangeListener;
import com.lishe.lishe.lishe.module.excitation.presenter.MinePresenter;
import com.lishe.lishe.lishe.utils.BitmapUtils;
import com.lishe.lishe.lishe.utils.SharedPreferencesUtils;
import com.lishe.lishe.lishe.utils.Utils;
import com.lishe.lishe.retrofit.BaseDataPageBody;
import com.lishe.lishe.retrofit.DataResponseListener;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.ResponseHandlerInterface;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.LinkedList;
import java.util.List;

import cz.msebera.android.httpclient.Header;

/**
 * Created by DELL on 2017/10/31.
 */

public class PersonDianZanActivity extends BaseActivity implements View.OnClickListener, OnDianZanWallClickListener {
    public static final int DIANZAN = 1;
    public static final int BEIZAN = 2;

    private static final int requestCode = 1;


    public static void jump(Activity activity, int type, String userId) {
        Intent intent = new Intent(activity, PersonDianZanActivity.class);
        intent.putExtra("type", type);
        intent.putExtra("userId", userId);
        activity.startActivity(intent);
    }

    private static final String TAG = PersonDianZanActivity.class.getSimpleName();

    private Button mBack;
    private TextView mTitle, mEmptyText, mTextError;
    private RecyclerView mRecylerView;
    private RelativeLayout mEmpty, mError;
    private SmartRefreshLayout mSmartRefreshLayout;

    private int page = 1, size = 20, totalPage;
    private DianZanWallAdapter adapter;
    private LinkedList<DianZanObject> dianzanList = new LinkedList<>();
    private String mUserId = null;
    private int type = BEIZAN;
    private int clickPosition = -1;


    @Nullable
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_person_dianzan);
        mUserId = getIntent().getStringExtra("userId");
        type = getIntent().getIntExtra("type", BEIZAN);

        initView();
        initListener();
        setAdapter();
        setSmartRefreshLayout();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PersonDianZanActivity.this.requestCode) {
            if (adapter != null) {
                adapter.notifyDataSetChanged();
            }
        } else if (requestCode == DianzanShareActivity.requestCode) {
            if (resultCode == RESULT_OK) {
                dianzanList.get(clickPosition).setShareCount(dianzanList.get(clickPosition).getShareCount() + 1);
                adapter.notifyDataSetChanged();
            }
        }
    }

    private void initView() {
        mBack = findViewById(R.id.title_left_button);
        mTitle = findViewById(R.id.title_text_title);
        mRecylerView = findViewById(R.id.list);
        mEmpty = findViewById(R.id.empty);
        mError = findViewById(R.id.error);
        mEmptyText = findViewById(R.id.empty_text);
        mTextError = findViewById(R.id.fresh);
        mEmptyText.setText("暂无数据");
        mTextError.setText("下拉刷新");
        mSmartRefreshLayout = findViewById(R.id.refreshlayout);

        mRecylerView.setLayoutManager(new LinearLayoutManager(PersonDianZanActivity.this));
        mRecylerView.addItemDecoration(new RecyclerLinearViewItemDecoration(Utils.dip2px(PersonDianZanActivity.this, 10), true));
        if (TextUtils.isEmpty(mUserId)) {
            if (type == BEIZAN) {
                mTitle.setText("我的被赞");
            } else {
                mTitle.setText("我的点赞");
            }

        } else {
            if (type == BEIZAN) {
                mTitle.setText("Ta的点赞");
            } else {
                mTitle.setText("Ta的点赞");
            }
        }
    }

    private void initListener() {
        mBack.setOnClickListener(this);
    }

    private void setAdapter() {
        adapter = new DianZanWallAdapter(PersonDianZanActivity.this, dianzanList, BitmapUtils.getDisplayWidth(this));
        adapter.setOnDianZanWallClickListener(this);
        mRecylerView.setAdapter(adapter);

        adapter.setOnItemClickListener(new RecyclerviewBaseAdapter.ItemListener.ItemClickListener() {
            @Override
            public void OnClickListener(RecyclerView.Adapter adapter, View view, int position) {
                DianZanDetailsActivity.jump(PersonDianZanActivity.this, dianzanList.get(position), requestCode);
            }
        });
    }

    private void setSmartRefreshLayout() {
        mSmartRefreshLayout.autoRefresh(0, 1, 0.62f);
        mSmartRefreshLayout.setEnableAutoLoadmore(true);//开启自动加载功能（非必须）

        mSmartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page = 1;
                getDianZanList();
                mSmartRefreshLayout.setLoadmoreFinished(false);//将会再次触发加载更多事件
                if(!mSmartRefreshLayout.isEnableLoadmore()) mSmartRefreshLayout.setEnableLoadmore(true);
            }
        });

        mSmartRefreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                //未加载完，可以LoadMore
                if (page <= totalPage) {
                    mSmartRefreshLayout.setLoadmoreFinished(false);//将会再次触发加载更多事件
                    getDianZanList();
                } else {
                    mSmartRefreshLayout.finishLoadmore();
                    mSmartRefreshLayout.setLoadmoreFinished(true);//将不会再次触发加载更多事件
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_left_button:
                finish();
                break;
        }
    }

    @Override
    public void onClickHead(String userId) {
        //点击头像跳转个人中心
        PersonExcitationActivity.jump(PersonDianZanActivity.this, userId);
    }

    @Override
    public void onClickImage(int position, int currentItem) {
        //点击图片放大
        showFullScreenDialog(position, currentItem);
    }

    @Override
    public void onClickForward(int position) {
        //点击转发
        clickPosition = position;
        DianzanShareActivity.jump(PersonDianZanActivity.this, dianzanList.get(position).getEventId(), dianzanList.get(position).getAvatarPath(), dianzanList.get(position).getEmpName(), dianzanList.get(position).getEventDesc());
    }

    @Override
    public void onClickGift(int position) {
        //点击送小礼
        clickPosition = position;
        if (dianzanList.get(position).getUserId().equals(Globals.getExcatationUserId())) {
            //跳转到小礼列表
            PersonReceiveGiftActivity.jump(PersonDianZanActivity.this, dianzanList.get(position).getEventId());
        } else {
            ShowSendGiftDialog.Builder builder = new ShowSendGiftDialog.Builder(PersonDianZanActivity.this);
            builder.setEventId(dianzanList.get(position).getEventId())
                    .setEventUserId(dianzanList.get(position).getUserId())
                    .setPointsType(1)
                    .setOnMessageChangeListener(listener);
            builder.show();
        }
    }

    @Override
    public void onClickComment(int position) {
        //点击评论
        clickPosition = position;
        ShowSendCommentDialog.Builder builder2 = new ShowSendCommentDialog.Builder(PersonDianZanActivity.this);
        builder2.setEventId(dianzanList.get(position).getEventId())
                .setOnMessageChangeListener(listener);
        builder2.show();
    }

    @Override
    public void onClickDianZan(int position) {
        //点击点赞
        clickPosition = position;

        if (dianzanList.get(position).getUserId().equals(Globals.getExcatationUserId())) {
            //跳转到小礼列表
            PersonReceiveAdmireActivity.jump(PersonDianZanActivity.this, dianzanList.get(position).getEventId());
        } else {
            if (dianzanList.get(position).isFlag()) {
                cancelHitEvent();
            } else {
                dianZanEvent();
            }
        }
    }

    private void showFullScreenDialog(int position, int currentItem) {
        ShowFullScreenImageDialog.Builder builder = new ShowFullScreenImageDialog.Builder(PersonDianZanActivity.this);
        builder.setCurrentItem(currentItem);
        builder.setBitmap(dianzanList.get(position).getImgList());
    }

    private OnMessageChangeListener listener = new OnMessageChangeListener() {
        @Override
        public void messageChange(int type, int changeNum) {
            if (type == OnMessageChangeListener.GIFT_CHANGE_SUCCESS) {
                dianzanList.get(clickPosition).setGiftCount(dianzanList.get(clickPosition).getGiftCount() + changeNum);
            } else if (type == OnMessageChangeListener.COMMENT_CHANGE_SUCCESS) {
                dianzanList.get(clickPosition).setCommentCount(dianzanList.get(clickPosition).getCommentCount() + changeNum);
            }
            adapter.notifyDataSetChanged();
        }
    };

    /**
     * 点赞事件
     */
    private void dianZanEvent() {
        try {
            MinePresenter.getInstance().hitEvent(Globals.getToken(), dianzanList.get(clickPosition).getEventId(), hitEventListener);
        } catch (Exception e) {
            e.printStackTrace();
            toast(getString(R.string.data_parse_fail));
        }
    }

    /**
     * 取消点赞事件
     */
    private void cancelHitEvent() {
        try {
            MinePresenter.getInstance().cancelHitEvent(Globals.getToken(), dianzanList.get(clickPosition).getEventId(), hitEventListener);
        } catch (Exception e) {
            e.printStackTrace();
            toast(getString(R.string.data_parse_fail));
        }
    }

    private DataResponseListener hitEventListener = new DataResponseListener() {
        @Override
        public void onSuccess(Object dataResponse) {
            if (dianzanList.get(clickPosition).isFlag()) {
//                        toast("取消点赞");
                dianzanList.get(clickPosition).setFlag(false);
                dianzanList.get(clickPosition).setAdmiredCount(dianzanList.get(clickPosition).getAdmiredCount() - 1);
            } else {
//                        toast("点赞成功");
                dianzanList.get(clickPosition).setFlag(true);
                dianzanList.get(clickPosition).setAdmiredCount(dianzanList.get(clickPosition).getAdmiredCount() + 1);
            }
            adapter.notifyDataSetChanged();
        }

        @Override
        public void onFail(String failMessage) {
            toast(failMessage);
        }

        @Override
        public void onError(Throwable e) {
            e.printStackTrace();
            toast(R.string.network_or_server_exception);
        }
    };

    /**
     * 获取点赞墙列表
     */
    private void getDianZanList() {
        if (mEmpty.getVisibility() == View.VISIBLE) {
            mEmpty.setVisibility(View.GONE);
        }
        if (mError.getVisibility() == View.VISIBLE) {
            mError.setVisibility(View.GONE);
        }
        try {
            MinePresenter.getInstance().getUserEventList(Globals.getToken(), mUserId, String.valueOf(type), String.valueOf(page), String.valueOf(size), new DataResponseListener<BaseDataPageBody<DianZanObject>>() {
                @Override
                public void onSuccess(BaseDataPageBody<DianZanObject> dataResponse) {
                    if (page == 1) {
                        mSmartRefreshLayout.finishRefresh(500, true);
                    } else {
                        mSmartRefreshLayout.finishLoadmore(500, true);
                    }

                    page++;
                    totalPage = dataResponse.getTotalPage();
                    dianzanList.clear();
                    dianzanList.addAll(dataResponse.getInfo());


                    if (dianzanList.size() > 0) {
                        adapter.notifyDataSetChanged();
                    } else {
                        mEmpty.setVisibility(View.VISIBLE);
                        mSmartRefreshLayout.setEnableLoadmore(false);
                    }
                }

                @Override
                public void onFail(String failMessage) {
                    //网络差是刷新界面显示1秒钟后消失
                    mSmartRefreshLayout.finishRefresh(1000, false);
                    mSmartRefreshLayout.finishLoadmore(1000, false);

                    toast(failMessage);
                    if (dianzanList.size() == 0) {
                        mSmartRefreshLayout.setLoadmoreFinished(true);//将不会再次触发加载更多事件
                        mError.setVisibility(View.VISIBLE);
                    }
                }

                @Override
                public void onError(Throwable e) {
                    //网络差是刷新界面显示1秒钟后消失
                    mSmartRefreshLayout.finishRefresh(1000, false);
                    mSmartRefreshLayout.finishLoadmore(1000, false);

                    e.printStackTrace();
                    toast(R.string.network_or_server_exception);
                    if (dianzanList.size() == 0) {
                        mSmartRefreshLayout.setLoadmoreFinished(true);//将不会再次触发加载更多事件
                        mError.setVisibility(View.VISIBLE);
                    }
                }
            });
        } catch (Exception e) {
            //网络差是刷新界面显示1秒钟后消失
            mSmartRefreshLayout.finishRefresh(1000, false);
            mSmartRefreshLayout.finishLoadmore(1000, false);

            e.printStackTrace();
            toast(getString(R.string.data_parse_fail));
            if (dianzanList.size() == 0) {
                mSmartRefreshLayout.setLoadmoreFinished(true);//将不会再次触发加载更多事件
                mError.setVisibility(View.VISIBLE);
            }
        }
    }

}
